package com.github.baichuan.gb32960.codec;

import com.github.baichuan.iot.protocol.pdu.Decoder;
import com.github.baichuan.iot.protocol.utils.DateTimeCodec;
import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 车辆登入
 */
public class Cmd01 implements Decoder {
    public static final Cmd01 INSTANCE = new Cmd01();

    @Override
    public List<Map<String, Object>> decode(ByteBuf buf) {
        Map<String, Object> data = new TreeMap<>();
        data.put("timestamp", DateTimeCodec.decode(buf));
        data.put("serialNo", buf.readUnsignedShort());
        data.put("iccid", buf.readCharSequence(20, StandardCharsets.US_ASCII).toString());

        // 可充电储能子系统数
        int bessQuantity = buf.readUnsignedByte();
        data.put("bessQuantity", bessQuantity);

        // 可充电储能子系统编码长度
        short bessCodeLength = buf.readUnsignedByte();
        data.put("bessCodeLength", bessCodeLength);

        // 可充电储能子系统编码
        String[] bessCodes = new String[bessQuantity];
        if(bessCodeLength > 0){
            for(int i = 0; i < bessQuantity; i++) {
                bessCodes[i] = buf.readCharSequence(bessCodeLength, StandardCharsets.US_ASCII).toString();
            }
        }
        data.put("bessCodes", bessCodes);

        return Arrays.asList(data);
    }
}
